<?php

function createGame($userId, $friendUserId, $categoryId, $numQuestions)
{
	$gameId = DB::insertId('games', array(
                    'id' => 0,
                    'first_user_id' => $userId,
                    'second_user_id' => $friendUserId,
                    'category_id' => $category,
                    'modified' => NOW(),
                    'created' => NOW()));

	$categories = getAllChildCategories($categoryId);

	$commated_string = "";
	foreach($categories as $key=>$category)
		$commated_string .= $category.",";
	$commated_string .= $categoryId;

	$questions = DB::query("SELECT id FROM questions WHERE category_id IN ($commated_string) " .
                               "ORDER BY RAND() LIMIT $noQuestions");
	$count = 0;
	foreach($questions as $question)
	{
		$question_id = $question['id'];
		DB::query("INSERT INTO games_questions(game_id,order_in_game,question_id) VALUES ('$game_id', '$count','$question_id')");
		$count++;
	}

	return $count
}

function getAllChildCategories($category_id){
	$categories = createArray("SELECT id FROM categories WHERE parent_id = $category_id");
	$added_categories = array();
	foreach($categories as $category){
		$cats = createCategories($category['id']);
		array_push($added_categories,$category['id']);
		foreach($cats as $cat){
			array_push($added_categories,$cat['id']);
		}
	}
	return $added_categories;
}
	
?>